#include "COMController.h"

HANDLE COM_Open(int NO){
	LPCTSTR comname;
	HANDLE h;
	switch (NO){
		case 1:
			comname = TEXT("COM1:");
			break;
		case 2:
			comname = TEXT("COM2:");
			break;
		case 3:
			comname = TEXT("COM3:");
			break;
		case 4:
			comname = TEXT("COM4:");
		default:
			return NULL;
			break;
	}
	h = CreateFile(comname,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
	if(h == INVALID_HANDLE_VALUE){
		printf("DBG:Error while opening COM%d:\n",NO);
		return NULL;
	}
	return h;
}

int COM_Close(HANDLE h){
	if(h==NULL) return 0;
	return CloseHandle(h);
}
int COM_SetPara(HANDLE h,struct COMPARA *compara){
	DCB dcb;
	int BaudRate;
	int Parity;
	int ByteSize;
	int StopBits;

	if(h == NULL) return 0;

	GetCommState(h,&dcb);

	switch(compara->BaudRate){
		case 19200:
			BaudRate = CBR_19200;
			break;
		default:
			return 0;
	}
	switch(compara->Parity){
		case 0:
			Parity = NOPARITY;
			break;
		default:
			return 0;
	}
	switch(compara->StopBits){
		case 0:
			StopBits = ONESTOPBIT;
			break;
		default:
			return 0;
	}
	ByteSize = compara->ByteSize;
	return SetCommState(h,&dcb);
}
int COM_Read(HANDLE h,int size,BYTE *buf){
	DWORD r;
	if(h == NULL) return 0;
	ReadFile(h,buf,size,&r,NULL);
	return r;
}
int COM_Write(HANDLE h,int size,BYTE *data){
	DWORD r;
	if(h == NULL) return 0;
	WriteFile(h,data,size,&r,NULL);
	return r;
}